package com.zygh.lz.controller.app;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.controller.FileUpload;
import com.zygh.lz.dao.SectionMapper;
import com.zygh.lz.entity.Section;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.app.*;
import com.zygh.lz.entity.bean.Entrance;
import com.zygh.lz.entity.bean.ParamParameter;
import com.zygh.lz.service.InformationService;
import com.zygh.lz.service.StaffService;
import com.zygh.lz.service.impl.AppDumpTrailerService;
import com.zygh.lz.service.impl.AppTrailerInfoService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.util.TreeUtil;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "司机拖车信息")
@RestController
@RequestMapping("/AppDumpTrailer")
@Slf4j
public class AppDumpTrailerController {

    @Resource
    private AppDumpTrailerService appDumpTrailerService;
    @Resource
    private AppTrailerInfoService appTrailerInfoService;
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private StaffService staffService;
    @Resource
    private InformationService informationService;
    @Resource
    private APPPushNotifications appPushNotifications;

    @Value("${trailer.picture-path}")
    private String picturePath;

    @ApiOperation("司机拖车信息上报(互联网122使用)")
    @RequestMapping(value = "/addDumpTrailer", method = RequestMethod.POST)
    public ResultBean addDumpTrailer(@RequestBody AppDumpTrailer appDumpTrailer) {
        System.out.println("司机上传code：" + appDumpTrailer.getCode());
        System.out.println("司机上传状态：" + appDumpTrailer.getStatus());
        AppDumpTrailer code = appDumpTrailerService.getOne(new QueryWrapper<AppDumpTrailer>()
                .eq("code", appDumpTrailer.getCode()));
        if (code != null) {
            return ResultUtil.setError(500, "编号重复", null);
        }
        String imagePath = null;
        if (StringUtils.isNotEmpty(appDumpTrailer.getPicture())) {
            try {
                imagePath = FileUpload.uploadImage(appDumpTrailer.getPicture(), picturePath);
            } catch (IOException | IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        boolean save = appDumpTrailerService.save(appDumpTrailer);

        if (save) {
            AppDriverPicture appDriverPicture = new AppDriverPicture();
            appDriverPicture.setCode(appDumpTrailer.getCode());
            appDriverPicture.setLatitude(appDumpTrailer.getLatitude());
            appDriverPicture.setLongitude(appDumpTrailer.getLongitude());
            appDriverPicture.setOrder(appDumpTrailer.getStatus());
            appDriverPicture.setPicture(imagePath);
            appDriverPicture.setCreatTime(DateUtil.parseDateTime(DateUtil.now()));
            int i = appDumpTrailerService.insertDriverPicture(appDriverPicture);

            //合并规则：民警上传信息不带拖车司机信息，拖车司机上传要带民警信息。
            // 其他字段不变。移除拖车司机记录表模块。仅保留民警拖车记录表模块。

            //图片
            AppPicture appPicture = new AppPicture();
            appPicture.setLatitude(appDumpTrailer.getLatitude());
            appPicture.setLongitude(appDumpTrailer.getLongitude());
            appPicture.setOrder(appDumpTrailer.getStatus());
            appPicture.setPicture(imagePath);
            appPicture.setCreatTime(DateUtil.parseDateTime(DateUtil.now()));
            //警员部门
            Staff staff = staffService.selectStaffByNum(appDumpTrailer.getPoliceNum());


            //无民警数据新增
            AppTrailerInfo appTrailerInfo = new AppTrailerInfo();
            BeanUtils.copyProperties(appDumpTrailer, appTrailerInfo);

            appTrailerInfo.setCode(appDumpTrailer.getCode());
            appTrailerInfo.setPhone(appDumpTrailer.getOwnerPhone());

            //判断你主次干道
            appTrailerInfo.setTrafficType(1);
            Section section1 = sectionMapper.selectByPrimaryKey(staff.getSysSectionId());
            List<AppTraffic> appTrafficById = appTrailerInfoService.findAppTrafficById(section1.getSectionPid());
            TreeUtil.trailerType(appTrafficById, appTrailerInfo);

            AppPark appPark = appTrailerInfoService.getAppPark(appDumpTrailer.getParkCode());
            appTrailerInfo.setWarningSignal(appDumpTrailer.getPoliceNum());
            appTrailerInfo.setStaffName(staff.getStaffName());
            appTrailerInfo.setSectionId(staff.getSysSectionId());
            appTrailerInfo.setSectionName(section1.getSectionName());
            appTrailerInfo.setStatus(appDumpTrailer.getStatus());
            appTrailerInfo.setCreatTime(DateUtil.parseDateTime(DateUtil.now()));
            appTrailerInfo.setStatus(appDumpTrailer.getStatus());
            appTrailerInfo.setDriverCode(appDumpTrailer.getCode());
            appTrailerInfo.setParkCode(appDumpTrailer.getParkCode());
            appTrailerInfo.setParkPlace(appPark.getName());
            appTrailerInfo.setDriverState(1);
            appTrailerInfo.setSignboard(0);
            appTrailerInfoService.save(appTrailerInfo);


            if (StringUtils.isNotEmpty(appDumpTrailer.getPicture())) {
                appPicture.setCode(appTrailerInfo.getCode());
                appTrailerInfoService.uploadTrailer(appPicture);
            }
            // 发短信
            AppNote appNote = new AppNote();
            appNote.setCode(appTrailerInfo.getCode());
            appNote.setPlate(appTrailerInfo.getVehiclePlate());
            appNote.setPlace(appTrailerInfo.getIllegalAddress());
            appNote.setAddress(appTrailerInfo.getParkPlace() + "地址：" + appPark.getAddress());
            //咨询电话
            Section section = sectionMapper.selectByPrimaryKey(appTrailerInfo.getSectionId());
            String contactWay = appPark.getContactWay();
            if (contactWay == null){
                contactWay="无";
            }
            appNote.setContact(contactWay+"/"+section.getHotline());
            appNote.setPhone(appTrailerInfo.getPhone());
            appNote.setCreatTime(new Date());
            appNote.setStatus(0);
            appTrailerInfoService.insertNote(appNote);

            //发送警务通通知
            ParamParameter paramParameter = new ParamParameter();
            List<Entrance> entrances = new ArrayList<>();
            Entrance entrance = new Entrance();
            entrance.setName(appDumpTrailer.getPoliceName());
            entrance.setSendWarningSignal(appDumpTrailer.getPoliceNum());
            entrances.add(entrance);
            paramParameter.setEntrances(entrances)
                    .setSendWarningSignal("admin")
                    .setMsgLevel("urgency")
                    .setTitle("拖车审批")
                    .setMsgdigest("请您进入交管警务APP审批最新的拖车信息!");
            appPushNotifications.batchSendPushMsg(paramParameter);
            return ResultUtil.execOp(i, "插入");
        }
        return ResultUtil.setError(SystemCon.RERROR1, "errot", null);

    }

    @ApiOperation("司机拖车信息更新(互联网122使用)")
    @RequestMapping(value = "/updateDumpTrailer", method = RequestMethod.POST)
    public ResultBean updateDumpTrailer(@RequestBody AppDumpTrailer appDumpTrailer) {
        System.out.println("司机上传code：" + appDumpTrailer.getCode());
        System.out.println("拖车信息状态更新：" + appDumpTrailer.getDriverState());

        boolean save = appDumpTrailerService.update(appDumpTrailer, Wrappers.<AppDumpTrailer>lambdaUpdate().eq(AppDumpTrailer::getCode, appDumpTrailer.getCode()));

        if (save) {

            AppTrailerInfo appTrailerInfo = new AppTrailerInfo();
            appTrailerInfo.setCode(appDumpTrailer.getCode());
            appTrailerInfo.setStatus(appDumpTrailer.getStatus());
            appTrailerInfo.setDriverState(appDumpTrailer.getDriverState());
            appTrailerInfo.setIsDel(appDumpTrailer.getIsDel());
            boolean update = appTrailerInfoService.update(appTrailerInfo, Wrappers.<AppTrailerInfo>lambdaUpdate().eq(AppTrailerInfo::getCode, appTrailerInfo.getCode()));

            return ResultUtil.execOp(update ? 1 : 0, "插入");
        }
        return ResultUtil.setError(SystemCon.RERROR1, "errot", null);

    }


    @ApiOperation("司机拖车信息上报(互联网122使用)")
    @RequestMapping(value = "/uploadPicture", method = RequestMethod.POST)
    public ResultBean addDumpTrailer(@RequestBody AppPicture appPicture) {
        //System.out.println("单独上报：" + appPicture);
        if (StringUtils.isEmpty(appPicture.getPicture())) {
            return ResultUtil.setError(SystemCon.RERROR1, "图片不能为空！", null);
        }
        String imagePath = null;
        try {
            log.info("互联网补充第二张照片：{}", appPicture.getCode());
            imagePath = FileUpload.uploadImage(appPicture.getPicture(), picturePath);
            appPicture.setPicture(imagePath);
        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return appTrailerInfoService.findPicture(appPicture);
    }


    @GetMapping("findDumpAll")
    public List<AppDumpTrailer> findDumpAll() {
        List<AppDumpTrailer> list = appDumpTrailerService.list();
        return list;
    }


    @ApiOperation("根据姓名和警号查询是否有这个民警(互联网使用)")
    @GetMapping("findPeopleBySignal")
    public ResultBean findPeopleBySignal(String warningSignal, String name) {
        if (StringUtils.isEmpty(warningSignal) && StringUtils.isEmpty(name)) {
            return ResultUtil.setError(SystemCon.RERROR1, "校验失败", false);
        }
        int count = staffService.count(new QueryWrapper<Staff>()
                .eq(StringUtils.isNotEmpty(warningSignal), "staff_num", warningSignal)
                .eq(StringUtils.isNotEmpty(name), "staff_name", name));
        if (count > 0) {
            return ResultUtil.setOK("校验成功", true);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "校验失败", false);
    }


    @ApiOperation("公安网拖车系统PC端上传图片")
    @RequestMapping(value = "/trailerUploadPicture", method = RequestMethod.POST)
    public ResultBean trailerUploadPicture(@RequestBody AppPicture appPicture) {
        //System.out.println("单独上报：" + appPicture);
        if (StringUtils.isEmpty(appPicture.getPicture())) {
            return ResultUtil.setError(SystemCon.RERROR1, "图片不能为空！", null);
        }
        String imagePath = null;
        try {
            imagePath = FileUpload.uploadImage(appPicture.getPicture(), picturePath);
        } catch (IOException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return ResultUtil.setOK("success", imagePath);
    }

}
